from typing import Union, Any

from fastapi import FastAPI, HTTPException
from config import skills, animal_configs
from model import AnimalVO, SkillVO

app = FastAPI()


@app.get("/skills", response_model=list[SkillVO])
def get_skills(category: Union[str, None] = None , is_hyper: Union[bool, None] = None,  q: Union[str, None] = None) -> Any:
    skill_list = [*skills]
    if category is not None:
        skill_list = [skill for skill in skill_list if skill.category == category]
    if is_hyper is not None:
        skill_list = [skill for skill in skill_list if skill.is_hyper == is_hyper]
    if q is not None:
        skill_list = [skill for skill in skill_list if q in skill.name]
    print(skill_list)
    return [
        SkillVO(
            is_hyper=skill.is_hyper,
            name=skill.name,
            bindable=skill.bindable,
            category=skill.category
        ) for skill in skill_list
    ]
    


@app.get("/match", response_model=AnimalVO)
def read_item(skills: list[str]):
    skill_set = set(skills)
    result = None
    # int最大值
    repeat = 2147483647
    for animal in animal_configs.values():
        animal_skill_set = set(map(lambda s: s.name, animal.skills))
        # 计算技能重复
        if len(animal_skill_set & skill_set) < repeat:
            repeat = len(animal_skill_set & skill_set)
            result = [animal]
    if result is None:
        raise HTTPException(status_code=404, detail="Item not found")
    return {
        "name": result[0].name,
        "skills": [SkillVO(is_hyper=skill.is_hyper, name=skill.name, bindable=skill.bindable, category=skill.category) for skill in result[0].skills],
        "necessary_skills": [SkillVO(is_hyper=skill.is_hyper, name=skill.name, bindable=skill.bindable, category=skill.category) for skill in result[0].necessary_skills],
        "level": result[0].level
    }